// 引入 react 依赖
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Text, View, TextInput, Image, TouchableOpacity, ImageBackground, ScrollView, Keyboard, InteractionManager, KeyboardAvoidingView } from 'react-native';

// 引入第三方依赖
import _ from 'lodash';
import pureRender from 'pure-render-decorator';
import { Actions } from 'react-native-router-flux';
import Icon from 'react-native-vector-icons/Ionicons';

// antd 按需加载
import { Tabs, Toast, Portal } from '@ant-design/react-native';

// 引入 处理数据 所需文件
import { cardDetail, cardCommentList, cardComment } from '../../module/module.js'

// 引入样式
import Style from './style/style.js';

// 引入公用组件
import { Status, NavBar, CacheImage, RnFlatList } from '../../components/index.js'

// 引入专用组件
import { CommentList } from './components'

// 引入工具包
import { } from '../../util/images.js';
import { press, size, ScreenWidth, borderBottom, borderTop, pathHead, requestCardLike, requestCardFollowAccount, defaultDataList, onEndReached, onRefresh, concatDataList, defaultPage } from '../../util/utils.js'

class CardPostDetail extends Component {

  constructor(props) {
    super(props)
    this.state = {
      refreshing: false,
      searchBackgroundColor: '#ccc',
      loading: false,
      detail: null,
      dataList: defaultDataList,
      commentUser: null,
      content: '',
      contentPlaceholder: '',
      autoFocus: false,
    }
  }

  componentDidMount() {
    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);

    InteractionManager.runAfterInteractions(() => {
      // ...耗时较长的同步的任务...
      this.showLoadingData()
      this.handleData().finally(() => { Portal.remove(this.loading) })
    });
  }

  componentWillUnmount() {
    this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener.remove();
  }

  _keyboardDidShow = () => {
    // alert('Keyboard Shown');
  }

  _keyboardDidHide = () => {
    this.setState({
      commentUser: null,
      contentPlaceholder: '',
    })
  }

  showLoadingData(options) {
    this.loading = Toast.loading('加载中', 0)
    this.loadingData(options).finally(() => {
      Portal.remove(this.loading)
    })
  }

  loadingData(options) {
    const { id } = this.props
    return Promise.all([cardDetail({ id })]).then(res => {
      console.log(res, '详情')
      this.setState({
        detail: res[0].data
      })
    })
  }

  handleData(options) {
    const { id } = this.props
    const { dataList: { current, size } } = this.state
    return new Promise((resolve, reject) => {
      cardCommentList({
        cardId: id,
        replyCommentId: 0,
        ...defaultPage.call(this),
        ...options
      }).then(res => {
        concatDataList.call(this, res)
        resolve(res)
      }).catch(error => {
        reject(error)
        console.log(error, 11111)
      })
    })
  }

  onRefresh = () => {
    onRefresh.call(this)
  }

  onEndReached = () => {
    onEndReached.call(this)
  }

  onScroll = (e) => {
    const { searchBackgroundColor } = this.state
    if (e.nativeEvent.contentOffset.y >= size(366) - 44) {
      this.setState({
        searchBackgroundColor: '#e43130'
      })
    } else {
      this.setState({
        searchBackgroundColor: 'transparent'
      })
    }
  }

  handleCardComment(replyId) {
    const { content, detail, commentUser } = this.state
    this.loading = Toast.loading('加载中', 0)
    let replyCommentId = replyId || 0
    console.log(commentUser)
    if (commentUser && commentUser.id) {
      replyCommentId = commentUser.id
    }
    cardComment({
      cardId: detail.id,
      replyCommentId,
      content: this.content._lastNativeText
    }).then(res => {
      this.onRefresh()
      this._keyboardDidHide()
      Keyboard.dismiss()
      this.content.clear()
      Toast.success(res.message)
    }).finally(() => {
      Portal.remove(this.loading)
    })
  }

  handleCardLike(options) {
    requestCardLike.call(this, options).then(res => {
      this.showLoadingData()
    })
  }

  handleCardFollowAccount(options) {
    requestCardFollowAccount.call(this, options).then(res => {
      this.showLoadingData()
    })
  }

  selectComment(data) {
    this.content.focus();
    this.setState({
      commentUser: data,
      contentPlaceholder: `@${data.nickname}`
    })
    // this.handleCardComment(data.id)
  }

  render() {
    const { id } = this.props
    const { refreshing, dataList, detail, commentUser, contentPlaceholder, autoFocus } = this.state
    return (
      <View style={Style.container}>
        <Status />
        <NavBar
          title="帖子详情"
          back={true}
        />
        <RnFlatList
          style={{
            flex: 1,
            backgroundColor: '#f0f2f5',
          }}
          onScroll={this.onScroll}
          refreshing={refreshing}
          onRefresh={this.onRefresh}
          onEndReached={this.onEndReached}
          removeClippedSubviews={true}
          data={dataList}
          ListHeaderComponent={() => {
            if (detail) {
              return (
                <View style={{}}>
                  <View style={{
                    backgroundColor: '#fff',
                  }}>
                    <View style={{
                      flexDirection: 'row',
                      justifyContent: 'space-between',
                      alignItems: 'center',
                      padding: 15,
                    }}>
                      <TouchableOpacity onPress={() => Actions.cardUserInfo({ id: detail.accountId })}>
                        <View style={{
                          flexDirection: 'row',
                          alignItems: 'center',
                        }}>
                          <CacheImage
                            resizeMod={"contain"}
                            style={{
                              marginRight: 5,
                              width: 22,
                              height: 22,
                              borderRadius: 10,
                              overflow: 'hidden'
                            }}
                            source={{ uri: `${pathHead}${detail.avatar}` }}

                          />
                          <Text style={{ fontSize: 16, color: '#8B8B8D', lineHeight: 18, }}>{detail.nickname}</Text>
                        </View>
                      </TouchableOpacity>
                      {detail.follow ? (
                        <TouchableOpacity
                          style={{
                            paddingVertical: 5,
                            paddingHorizontal: 15,
                            borderRadius: 10,
                            borderWidth: 1,
                            borderColor: '#000000'
                          }}
                          onPress={() => {
                            this.handleCardFollowAccount({ id: detail.accountId, type: 0 })
                          }}
                        >
                          <Text style={{ fontSize: 16, color: '#8B8B8D', lineHeight: 18, }}>取消关注</Text>
                        </TouchableOpacity>
                      ) : (
                          <TouchableOpacity
                            style={{
                              paddingVertical: 5,
                              paddingHorizontal: 15,
                              borderRadius: 10,
                              borderWidth: 1,
                              borderColor: '#000000'
                            }}
                            onPress={() => {
                              this.handleCardFollowAccount({ id: detail.accountId, type: 1 })
                            }}
                          >
                            <Text style={{ fontSize: 16, color: '#8B8B8D', lineHeight: 18, }}>关注</Text>
                          </TouchableOpacity>
                        )}
                    </View>
                    <View style={{
                      paddingHorizontal: 15,
                      marginBottom: 20
                    }}>
                      <Text style={{ fontSize: 14, color: '#8B8B8D', lineHeight: 16, }}>{detail.title}</Text>
                      {/* {imageList.map((item, index) => {
                        return (
                          <TouchableOpacity
                            key={index}
                            onPress={() => this.deleteImageListItem(index)}
                            style={{ marginRight: 10 }}
                          >
                            <Image resizeMode='cover' style={{ width: 88, height: 88, borderWidth: 1, borderColor: '#eee' }} source={{ uri: `${pathHead}${item}` }} />
                          </TouchableOpacity>
                        )
                      })} */}
                    </View>
                    <View style={{
                      marginBottom: 10,
                      paddingTop: 10,
                      flexDirection: 'row',
                      alignItems: 'center',
                      ...borderTop()
                    }}>
                      <View style={{ flex: 1 }} >
                        <View style={{
                          flexDirection: 'row',
                          alignItems: 'center',
                          justifyContent: 'center',
                        }}>
                          <Icon name="ios-chatbubbles" size={20} color={'#61676F'} />
                          <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, marginLeft: 10 }}>{detail.commentCount}</Text>
                        </View>
                      </View>
                      <TouchableOpacity style={{ flex: 1 }} onPress={() => this.handleCardLike({ id: detail.id, type: detail.like ? 0 : 1 })}>
                        <View style={{
                          flexDirection: 'row',
                          alignItems: 'center',
                          justifyContent: 'center',
                        }}>
                          <Icon name="ios-heart" size={20} color={detail.like ? '#E5C67B' : '#61676F'} />
                          <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, marginLeft: 10 }}>{detail.likeCount}</Text>
                        </View>
                      </TouchableOpacity>
                      <View style={{
                        flexDirection: 'row',
                        alignItems: 'center',
                        justifyContent: 'center',
                        flex: 1,
                      }}>
                        <Icon name="ios-person" size={20} color={'#61676F'} />
                        <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, marginLeft: 10 }}>{detail.readCount}</Text>
                      </View>
                    </View>
                  </View>
                  <View style={{ padding: 15, marginTop: 10, backgroundColor: '#fff' }}>
                    {detail.goodsList && detail.goodsList.map((item, index) => {
                      return (
                        <TouchableOpacity
                          key={index}
                          onPress={() => Actions.goodDetails({ goodsId: item.id, productId: item.productId, })}
                          style={{ marginBottom: 10 }}
                        >
                          <View style={{ flexDirection: 'row', alignItems: 'center', padding: 10, backgroundColor: '#EFEFEF' }}>
                            <Image resizeMode='cover' style={{ width: 88, height: 88, borderWidth: 1, borderColor: '#eee' }} source={{ uri: `${pathHead}${item.goodsMainPic}` }} />
                            <View style={{ marginLeft: 10, flex: 1 }}>
                              <Text ellipsizeMode="tail" numberOfLines={2} style={{ fontSize: 16, color: '#61676F', lineHeight: 18, marginBottom: 10 }}>{item.goodsName}</Text>
                              <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>{item.goodsPrice}</Text>
                            </View>
                          </View>
                        </TouchableOpacity>
                      )
                    })}
                    <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>{detail.content}</Text>
                  </View>
                  <View style={{}}>
                    <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, marginTop: 10, marginBottom: 10, paddingHorizontal: 15 }}>评论列表</Text>
                  </View>
                </View>
              )
            }
            return null
          }}
          renderItem={({ item }) => {
            return (
              <View style={{
                padding: 15,
                backgroundColor: '#fff',
                ...borderTop()
              }}>
                <TouchableOpacity
                  onPress={() => {
                    this.selectComment(item)
                  }}
                >
                  <View style={{}}>
                    <View style={{ flexDirection: 'row', alignItems: 'center', }}>
                      <CacheImage
                        resizeMod={"contain"}
                        style={{
                          marginRight: 5,
                          width: 22,
                          height: 22,
                          borderRadius: 10,
                          overflow: 'hidden'
                        }}
                        source={{ uri: `${pathHead}${item.avatar}` }}

                      />
                      <Text style={{ flex: 1, fontSize: 16, color: '#8B8B8D', lineHeight: 18, }}>{item.nickname}</Text>
                    </View>
                    <View style={{ marginLeft: 27 }}>
                      <Text style={{ fontSize: 14, color: '#61676F', lineHeight: 16, }}>{item.content}</Text>
                    </View>
                    <View style={{ marginLeft: 27, flexDirection: 'row', alignItems: 'center', }}>
                      <Text style={{ fontSize: 10, color: '#61676F', lineHeight: 14, }}>{item.createTime}</Text>
                      <Text style={{ fontSize: 10, color: '#61676F', lineHeight: 14, marginLeft: 10, paddingHorizontal: 8, paddingVertical: 5, backgroundColor: '#D8D8D8', borderRadius: 12 }}>{item.replyCount}回复</Text>
                    </View>
                  </View>
                </TouchableOpacity>
                <View style={{ paddingLeft: 27 }}>
                  {item.replyCount > 0 && <CommentList pid={id} id={item.id} selectComment={(data) => this.selectComment(data)} />}
                </View>
              </View>
            )
          }}
        />
        <KeyboardAvoidingView behavior="padding" enabled>
          <View style={{ paddingHorizontal: 15, paddingVertical: 8, backgroundColor: '#fff', flexDirection: 'row', }}>
            <View style={{ backgroundColor: '#EDEEEF', borderRadius: 16, paddingHorizontal: 10, flex: 1 }}>
              <TextInput
                style={{ textAlignVertical: 'top', padding: 5, lineHeight: 22 }}
                multiline
                placeholder={contentPlaceholder || "写评论"}
                // onChangeText={(value) => this.setState({ content: value })}
                // autoFocus={autoFocus}
                ref={(r) => this.content = r}
              />
            </View>
            <TouchableOpacity
              style={{
                paddingVertical: 5,
                paddingHorizontal: 10,
                borderRadius: 10,
                borderWidth: 1,
                borderColor: '#000000',
                marginLeft: 15
              }}
              onPress={() => {
                this.handleCardComment()
              }}
            >
              <Text style={{ fontSize: 12, color: '#8B8B8D', lineHeight: 16, }}>发送</Text>
            </TouchableOpacity>
          </View>
        </KeyboardAvoidingView>
      </View >
    );
  }
}


export default connect(({ user }) => ({
  user,
}))(pureRender(CardPostDetail))
